package cn.szzsi.platform.controller.admin;

import cn.szzsi.common.bean.SystemConfig;
import cn.szzsi.common.controller.BaseController;
import cn.szzsi.common.util.CommonUtil;
import cn.szzsi.common.util.EHcacheUtil;
import cn.szzsi.common.util.StringUtils;
import cn.szzsi.common.util.SystemConfigUtil;
import cn.szzsi.core.kit.HttpRequestUtils;
import cn.szzsi.model.*;
import cn.szzsi.platform.service.AdminService;
import cn.szzsi.platform.validator.AdminValidator;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Duang;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.redis.Redis;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.time.DateUtils;

import javax.servlet.http.Cookie;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;

/**
 * 后台类 - 后台管理、管理员
 */
//@Before(NavigationInterceptor.class)
public class AdminController extends BaseController<Admin> {
    public static ScheduledExecutorService ses;

    private Admin admin;
    // sys登录页面
    @Clear
    public void login() {
        SystemConfig systemConfig = SystemConfigUtil.getSystemConfig();
        setAttr("systemConfig", systemConfig);
        setAttr("base", getRequest().getContextPath());
        render(CommonUtil.TEMPLATE_PATH + "/platform/admin/sys_login.html");
    }
    // 管理员退出
    @Clear
    public void logout() {
        //移除会员登陆_auth(可以凭借_auth换取用户信息)
        Cookie authCookie = new Cookie("_authAdmin",null);//登录类型
        authCookie.setPath(getRequest().getContextPath()+"/");
        authCookie.setMaxAge(0);
        setCookie(authCookie);
        redirect("/sys/login");
    }

    /**
     * L登录（超级管理员管理员）
     */
    @Clear
    public void singIn() {
        String userName = getPara("username", "");
        String passWord = getPara("password", "");
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(passWord)) {
            renderJson(Ret.fail("info","用户名和密码不能为空"));
            return;
        }
        if (!Admin.dao.isExistAdmin(userName)) {
            renderJson(Ret.fail("info","用户不存在"));
            return;
        }

        Admin sysAdmin = Admin.dao.getSysAdmin(userName, passWord);//商户

        if (sysAdmin == null) {
            renderJson(Ret.fail("info","用户名或密码错误"));
            return;
        }
        String loginIp= null;
        try {
            loginIp = HttpRequestUtils.getIpAddr(getRequest());
        } catch (Exception e) {
            e.printStackTrace();
        }
        sysAdmin.setLoginIp(loginIp);
        sysAdmin.update();

        //写入会员登陆_auth(可以凭借_auth换取用户信息)
        String _authAdmin=StrKit.getRandomUUID();//超级管理员登陆授权码
        Cookie authCookie = new Cookie("_authAdmin",_authAdmin);//登录类型
        authCookie.setPath(getRequest().getContextPath()+"/");
        setCookie(authCookie);

        //将上一步的auth存入Redis缓存服务器
        Map map=new HashMap();
        map.put("id",sysAdmin.getId());
        map.put("username",sysAdmin.getUsername());
        Redis.use("zshop").setex(_authAdmin,3600, JsonKit.toJson(map));
        renderJson(Ret.ok());
    }


    /**
     * L登录进入首页
     */
    public void indexv2() {
        String userId=getAttr("userId");
        Admin admin=Admin.dao.findById(userId);
        setAttr("admin",admin);
        AdminService.service.filterRoleResource(getRequest(),admin);
        setAttr("plateformConfig",PlateformConfig.dao.findById("1"));
        render(CommonUtil.TEMPLATE_PATH + "/platform/index/sys_login_head.html");
    }

    public void indexv3(){
        String userId=getAttr("userId");
        Admin admin=Admin.dao.findById(userId);
        setAttr("admin",admin);
        setAttr("plateformConfig",PlateformConfig.dao.findById("1"));
        render(CommonUtil.TEMPLATE_PATH + "/platform/index/indexv3.html");
    }
    public void indexv3Json(){
        String userId=getAttr("userId");
        Admin admin=Admin.dao.findById(userId);
        List<Object> firstList= CacheKit.get(EHcacheUtil.PLATEFORM_RESOURCE_MENU,admin.getRoleId());
        if(firstList==null){
            firstList=new ArrayList();
            List<PlatformResource> firstMenu = PlatformResource.dao.getByLevelAndRoleId(1,admin.getRoleId());//一级菜单
            //将一级菜单放入json
            for(PlatformResource firstResource:firstMenu){

                //根据一级菜单查询二级菜单
                List<PlatformResource> secondMenu=PlatformResource.dao.getByPidAndRoleId(firstResource.getId(),admin.getRoleId());
                List<Object> secondList=new ArrayList();
                for(PlatformResource secondResource:secondMenu){

                    //根据二级菜单查询三级菜单
                    List<PlatformResource>threeMenu=PlatformResource.dao.getByPidAndRoleId(secondResource.getId(),admin.getRoleId());
                    List<Object>threeList=new ArrayList();
                    for(PlatformResource threeResource:threeMenu){
                        Map threeMap=new HashMap();
                        threeMap.put("thirdDary",threeResource.getName());
                        threeMap.put("page",threeResource.getUrl());
                        threeList.add(threeMap);
                    }

                    Map seonndMap=new HashMap();//二级菜单map
                    seonndMap.put("secondDary",secondResource.getName());
                    seonndMap.put("icon",secondResource.getIcon());
                    seonndMap.put("list",threeList);
                    secondList.add(seonndMap);

                }
                Map firstMap=new HashMap();//一级菜单map
                firstMap.put("id",firstResource.getId());
                firstMap.put("firstdary",firstResource.getName());
                firstMap.put("list",secondList);
                firstList.add(firstMap);

            }
            CacheKit.put(EHcacheUtil.PLATEFORM_RESOURCE_MENU,admin.getRoleId(),firstList);
        }

        renderJson(JsonKit.toJson(firstList));

    }


}
